import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState } from "react";
import { useBaseIngredients, BaseIngredient } from "src/hooks/useBaseIngredients";
import { request } from "src/request";
import { AtActionSheet, AtActionSheetItem, AtButton, AtFloatLayout, AtList, AtListItem } from "taro-ui";
import { Input } from "src/components/input";
import { showModal } from "src/utils/modal";
import { showToast } from "src/utils/toast";

function BaseIngredientView() {
  const [baseIngredients = [], fetchBaseIngredients] = useBaseIngredients()
  const [isEditOpened, setIsEditOpened] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [isActionSheetOpened, setActionSheetOpened] = useState(false)
  const [data, setData] = useState<BaseIngredient>({
    name: '',
  })
  const [tmpData, setTmpData] = useState<BaseIngredient>()

  function createBaseIngredient(baseIngredientData) {
    return request.post('/base-ingredient', baseIngredientData)
  }

  function updateBaseIngredient(baseIngredientData: BaseIngredient) {
    return request.put(`/base-ingredient/${baseIngredientData.id}`, baseIngredientData)
  }

  function removeBaseIngredient(id) {
    return request.delete(`/base-ingredient/${id}`)
  }

  function handleChange(type: keyof BaseIngredient) {
    return (value) => {
      setData({
        ...data,
        [type]: value
      })
    }
  }

  function handleAdd() {
    setIsEdit(false)
    setData({
      name: '',
    })
    setIsEditOpened(true)
  }

  function handleClickItem(baseIngredient) {
    return () => {
      setTmpData(baseIngredient)
      setActionSheetOpened(true)
    }
  }

  function handleEdit() {
    if (tmpData) {
      setIsEdit(true)
      setData(tmpData)
      setActionSheetOpened(false)
      setIsEditOpened(true)
    }
  }

  async function handleRemove() {
    if (tmpData) {
      setActionSheetOpened(false)
      const { confirm } = await showModal({
        title: '确认删除',
        content: `确认删除「${tmpData.name}」吗？删除后使用该调料的准备材料将会异常`,
      })
      if (confirm) {
        removeBaseIngredient(tmpData.id).then(() => {
          Taro.showToast({
            title: '删除成功',
            icon: 'none',
          })
          fetchBaseIngredients()
        })
      } else {
        showToast('已取消删除')
      }
    }
  }

  function handleSubmit() {
    if (!data.name) {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none',
      })
      return
    }
    (isEdit ? updateBaseIngredient(data) : createBaseIngredient(data)).then(() => {
      Taro.showToast({
        title: '保存成功',
        icon: 'none',
      })
      fetchBaseIngredients()
      setIsEditOpened(false)
    })
  }

  return (
    <View>
      <View className='header'>
        <View className='header-name'>
          基础调料
        </View>
      </View>
      <View className='body'>
        <AtList hasBorder={false}>
          {
            baseIngredients.map(baseIngredient => (
              <AtListItem title={baseIngredient.name} key={baseIngredient.id} onClick={handleClickItem(baseIngredient)} />
            ))
          }
        </AtList>
        <AtButton type='primary' size='normal' onClick={handleAdd}>添加基础调料</AtButton>
        <AtFloatLayout isOpened={isEditOpened} title='添加基础调料' onClose={() => setIsEditOpened(false)}>
          <Input
            name='name'
            title='调料名'
            placeholder='请输入调料名'
            border={false}
            required
            value={data.name}
            onChange={handleChange('name')}
            hidden={!isEditOpened}
          />
          <Input
            name='unit'
            title='单位'
            placeholder='请输入单位'
            border={false}
            required
            value={data.unit}
            onChange={handleChange('unit')}
            hidden={!isEditOpened}
          />
          <AtButton type='secondary' onClick={handleSubmit}>提交</AtButton>
        </AtFloatLayout>
        <AtActionSheet isOpened={isActionSheetOpened} cancelText='取消' onClose={() => setActionSheetOpened(false)}>
          <AtActionSheetItem onClick={handleEdit}>
            编辑
          </AtActionSheetItem>
          <AtActionSheetItem onClick={handleRemove}>
            删除
          </AtActionSheetItem>
        </AtActionSheet>
      </View>
    </View>
  );
}

export default BaseIngredientView;
